๐Ÿšจ Java Exception Handling - Complete Guide

๐Ÿง  1. What is an Exception?

An exception is an event that disrupts normal flow of the program at runtime.

๐Ÿงƒ Real-Life Example:

Imagine you're using an ATM:

  • You try to withdraw โ‚น5000, but your balance is โ‚น1000
  • ๐Ÿ’ฅ The system throws an InsufficientBalanceException

๐Ÿงฑ Java Program Example:

int a = 10;
int b = 0;
int result = a / b;  // โŒ ArithmeticException: divide by zero

๐Ÿ”บ Throwable Class

The Throwable class is the root of Javaโ€™s exception hierarchy. Every exception or error object in Java is a subclass of Throwable.

๐Ÿ“ฆ Two Main Subclasses of Throwable

Exception Hierarchy

๐Ÿ” Exception Class (Recoverable)

The Exception class represents problems that can be handled programmatically.

โœ… Checked Exceptions

โš ๏ธ Unchecked Exceptions (Runtime)

๐Ÿšซ Error Class (Unrecoverable)

The Error class indicates serious problems that applications should not attempt to catch.

๐Ÿงฉ 3. try-catch-finally

try-catch-finally

๐Ÿ”ง Syntax:

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Code to handle the specific exception
} finally {
    // Code that always executes (cleanup, closing files, etc.)
}

โœ… Example:

try {
    int result = 10 / 0;  // This will throw ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!"); // This will run
} finally {
    System.out.println("Cleanup done!"); // This will always run
}

๐Ÿ“ Output:

๐Ÿ“Œ Note: The finally block will always execute whether an exception is thrown or not. It's used to release resources like file handles, database connections, etc.

๐Ÿงช 4. throw vs throws

throw vs throws

๐Ÿง  Hinglish Explanation:

Keyword Meaning Used In
throw Used to manually throw an exception Inside method body
throws Used to declare that a method may throw an exception In method signature

โœ… Example 1: Using throw

void validateAge(int age) {
    if (age < 18) {
        throw new IllegalArgumentException("Invalid age: must be 18 or above");
    }
    System.out.println("Valid age!");
}

Output: Agar age 15 hai to: Invalid age: must be 18 or above

โœ… Example 2: Using throws

import java.io.*;

void readFile() throws IOException {
    FileReader fr = new FileReader("file.txt");
    // This may throw IOException
}

Note: Method ke signature mein throws IOException likhne se compiler ko pata chalta hai ki is method mein exception aa sakta hai.

๐Ÿ’ก Tip: Aksar interview mein yeh puchte hain: "throw vs throws difference?"

Answer: throw ka use exception ko actually throw karne ke liye hota hai, jabki throws batata hai ki method se exception aa sakta hai.

๐Ÿ— 5. Custom Exception

Create your own exception class:

class AgeException extends Exception {
    AgeException(String msg) {
        super(msg);
    }
}

Use it:

if (age < 18) {
    throw new AgeException("Not eligible");
}

๐Ÿ”„ 6. final vs finally vs finalize()

๐Ÿง  Hinglish Explanation:

Keyword Use
final Prevent change (used with variables, methods, class)
finally Always runs after try-catch (cleanup)
finalize() Called by Garbage Collector before destroying object (deprecated)

โœ… finalize() Example:

class Demo {
    protected void finalize() throws Throwable {
        System.out.println("๐Ÿ—‘๏ธ Object is being destroyed by GC");
    }
}

public class Test {
    public static void main(String[] args) {
        Demo obj = new Demo();
        obj = null; // make eligible for GC

        System.gc(); // request garbage collection
        System.out.println("Main complete");
    }
}

๐Ÿ“ Output ho sakta hai: Main complete ke baad finalize() message aaye

โš ๏ธ Note: finalize() is deprecated in Java 9+. Use AutoCloseable or try-with-resources instead.

๐Ÿ” 7. try-with-resources (Best Practice)

Automatically closes resources like files or DB connections.

try (FileReader fr = new FileReader("data.txt")) {
    // use file
} catch (IOException e) {
    e.printStackTrace();
}

๐Ÿ“ Interview Summary

Concept Notes
Throwable Base class of Error & Exception
Checked Exception Must handle using try-catch or throws
Unchecked Occurs at runtime
throw Manually throw exception
throws Declare possible exception
finally Always executes for cleanup
finalize() Called by GC (now deprecated)

๐Ÿ”ฅ Interview Q&A

Q1: What is the difference between checked and unchecked exceptions?

โœ… Checked: Must be handled (IOException)

โŒ Unchecked: Runtime errors (NullPointerException)

Q2: What is the difference between throw and throws?

  • throw: throw exception manually
  • throws: declare in method signature

Q3: What is finalize()?

  • Method called by Garbage Collector before object is destroyed
  • Deprecated, not reliable for cleanup